using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using UniversalAdminSystem.Domian.PermissionManagement.Aggregate;
using UniversalAdminSystem.Domian.PermissionManagement.IRepository;
using UniversalAdminSystem.Domian.PermissionManagement.ValueObjects;
using UniversalAdminSystem.Domian.PermissionManagement.Services;

namespace UniversalAdminSystem.Infrastructure.Services;

public class PermissionInitializationService : IHostedService
{
    private readonly SystemPermissionConfigLoader _loader;
    private readonly IServiceScopeFactory _scopeFactory;
    private static bool _initialized = false;

    public PermissionInitializationService(
        SystemPermissionConfigLoader loader,
        IServiceScopeFactory scopeFactory
    )
    {
        _loader = loader;
        _scopeFactory = scopeFactory;
    }

    public async Task StartAsync(CancellationToken cancellationToken)
    {
        if (_initialized)
        {
            return;
        }

        cancellationToken.ThrowIfCancellationRequested();

        try
        {
            // 首先加载权限规则配置
            var rulesConfigPath = Path.Combine(AppContext.BaseDirectory, "PermissionRules.json");
            if (File.Exists(rulesConfigPath))
            {
                var rulesContent = await File.ReadAllTextAsync(rulesConfigPath, cancellationToken);
                var rulesDict = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, List<string>>>(rulesContent);
                
                if (rulesDict != null)
                {
                    var rules = rulesDict.ToDictionary(
                        kv => Enum.Parse<PermissionAction>(kv.Key, true),
                        kv => kv.Value.ToHashSet()
                    );
                    
                    ResourceActionValidator.LoadRules(rules);
                    Console.WriteLine("权限规则配置加载成功");
                }
            }
            else
            {
                Console.WriteLine("权限规则配置文件不存在，使用默认配置");
                // 设置默认规则
                var defaultRules = new Dictionary<PermissionAction, HashSet<string>>
                {
                    { PermissionAction.Read, new HashSet<string> { "data", "file", "user", "role", "permission", "config", "system" } },
                    { PermissionAction.Create, new HashSet<string> { "data", "user", "file", "role", "permission" } },
                    { PermissionAction.Update, new HashSet<string> { "data", "user", "config", "role", "permission" } },
                    { PermissionAction.Delete, new HashSet<string> { "data", "user", "file", "role", "permission" } },
                    { PermissionAction.Manage, new HashSet<string> { "system", "user" } }
                };
                ResourceActionValidator.LoadRules(defaultRules);
            }

            // 加载配置文件
            var configPath = Path.Combine(AppContext.BaseDirectory, "SystemPermissions.json");
            var permissions = await _loader.LoadFromFileAsync(configPath);

            // 初始化到数据库
            using (var scope = _scopeFactory.CreateScope())
            {
                var permissionRepository = scope.ServiceProvider.GetRequiredService<IPermissionRepository>();

                var systemPermissions = new List<Permission>();
                foreach (var perm in permissions)
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    if (!Enum.TryParse<PermissionAction>(perm.Action, out var action))
                    {
                        throw new InvalidOperationException($"无效的权限操作: {perm.Action}");
                    }

                    var sysPerm = Permission.CreateSystemPermission(perm.Name, perm.Resource, (int)action);
                    systemPermissions.Add(sysPerm);
                }
                
                // 持久化
                await permissionRepository.AddSystemPermissionsAsync(systemPermissions);
                Console.WriteLine($"成功初始化 {systemPermissions.Count} 个系统权限");
            }

            _initialized = true;
        }
        catch (Exception ex)
        {
            throw new InvalidOperationException("初始化系统权限失败", ex);
        }
    }

    public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}